package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.exception.BusinessException;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private AdminService adminService;

    // 生成验证码
    public LineCaptcha verification(String uuid) {
        // 1.hutool生成验证码
        LineCaptcha lineCaptcha = new LineCaptcha(300, 100);

        // 2.将正确验证码存储到redis中（5分钟）
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + uuid, lineCaptcha.getCode(), Duration.ofMinutes(5));

        // 3.返回验证码对象
        return lineCaptcha;

    }

    // 管理员登录
    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        // 1.根据uuid取出redis验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        // 2.对比验证码
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            throw new BusinessException("验证码不匹配");
        }
        // 3.根据username查询admin对象
        Admin admin = adminService.findByUsername(username);
        if (admin == null) {
            throw new BusinessException("用户名不存在");
        }
        // 4.对比密码
        String pwd = SecureUtil.md5(password);
        if (!StrUtil.equals(pwd, admin.getPassword())) {
            throw new BusinessException("密码不正确");
        }
        // 5.销毁验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);
        // 6.制作token
        admin.setPassword(null);
        Map<String, Object> map = BeanUtil.beanToMap(admin);
        String token = JwtUtil.createToken(map);
        // 7.redis续期
        String json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));
        // 8.返回token
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        return ResponseEntity.ok(result);

    }

    // 管理员信息
    public ResponseEntity profile(String token) {
        // 1.根据token查询redis中json
        // 处理前端工程师携带 Bearer (此处有空格)
        token = token.replaceAll("Bearer ", "");
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        // 如果没查到
        if (StrUtil.isEmpty(json)) {
            throw new BusinessException("用户登录超时。。。");
        }
        // 2.将json转为admin对象
        Admin admin = JSON.parseObject(json, Admin.class);

        // 3.续期1小时
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));

        // 4.返回admin
        return ResponseEntity.ok(admin);
    }

    // 管理员退出
    public void logout(String token) {

        // 处理前端传递token的Bearer （此处有空格）
        token = token.replaceAll("Bearer ", "");
        // 清除redis的token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
